<!--
 * play_with_boards.htm - Javascript chess library
 *
 * http://code.google.com/p/fics-meets-html5/
 *
 * Copyright 2012 Markus Kupke
 */  -->

<html>
<head>
<title>Play with boards</title>
<link rel="stylesheet" type="text/css" href="chessboard.css">
</link>
</head>
<body>
	<script src="js/app/position_internals.js">
	</script>
	<script src="js/app/chessboard_internals.js">
	</script>
	<script>
		onload = function() {
//			game = new chesslib.Position();
			var game = new chesslib.Position("8/3P3p/p1N3pk/2PB1p2/3n1P2/P5P1/1q5P/3R3K w - - 0 41");
			var chessboard_div = document.getElementById("first");
			var boardnode = chesslib.board.createBoardInElement(chessboard_div);
			boardnode.chess.setFigures(game.toJSON());
			var movesArray = game.legalmoves().toString().split(',');
			moves = {};
			movesArray.forEach(function(v){
			  var from = v.slice(1,3);
			  var to = v.slice(4,6);
			  if ( v.length > 6 ) {
				to += '?'; 			  	
			  }; 
			  if(!(moves[from])) moves[from] = [];
			  if(moves[from].indexOf(to)===-1) moves[from].push(to);
			});
			var func = function () {
				var fromK = Object.keys(boardnode.chess.move);
				if (fromK.length > 2) throw new Error ("move property of board malformed");
				var fromS = fromK[0].length > 2 ? fromK[1]:fromK[0];
				var toS = boardnode.chess.move[fromS];
				var from = ("abcdefgh".indexOf(fromS[0]) + 1) + (parseInt(fromS[1]) + 1) * 10; 
				var to = ("abcdefgh".indexOf(toS[0]) + 1) + (parseInt(toS[1]) + 1) * 10; 
				var userMoveArray = game.legalmoves().filter(function(m){return (m.from === from && m.to === to)});
				if (userMoveArray.length === 0) throw new Error("Fatal: this should never happen. The user was able to make an illegal move");
				if (userMoveArray.length === 1) {
				   var userMove = userMoveArray[0];
				} else {
					userMoveArray = userMoveArray.filter(function(m){return (m.changetofigure.toUpperCase() === boardnode.chess.move.promotion )});
  				    var userMove = userMoveArray[0];
				};
				game = game.move(userMove);
				boardnode.chess.setFigures(game.toJSON());
				var movesArray = game.legalmoves().toString().split(',');
				moves = {};
				movesArray.forEach(function(v){
				  var from = v.slice(1,3);
				  var to = v.slice(4,6);
				  if ( v.length > 6 ) {
					to += '?'; 			  	
				  }; 
				  if(!(moves[from])) moves[from] = [];
				  if(moves[from].indexOf(to)===-1) moves[from].push(to);
				});
				boardnode.chess.setPossibleMoves(moves, func);		
			};
			boardnode.chess.setPossibleMoves(moves, func);		
		};
	</script>
	<div id='first'></div>
</body>
</html>